import { constantRoutes, asyncRoutes } from '../../router/index.js'

const hasPermission = (route, roles) => {
    if (route.meta && route.meta.roles) {
       
        return roles.some(role => route.meta.roles.includes(roles))
        
        
    } else {
        return
    }
}


const filterAsyncRoutes = (routes, roles) => {
    const res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(tmp, roles)) {
            res.push(tmp)
        }
    })
    return res
}


const state = {
    routes: []
}

const mutations = {
    SET_ROUTES(state, routes) {
        state.routes = constantRoutes.concat(routes)
    }
}


const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise((resolve, reject) => {
            let accessedRoutes
            if (roles.includes("admin")) {
                accessedRoutes = asyncRoutes
            } else {
                accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
            }
            commit("SET_ROUTES", accessedRoutes)
            resolve(accessedRoutes)
        })
    },

}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}